from collections import namedtuple
from functools import wraps
import inspect
from typing import Any, Callable, Coroutine, TypeVar
from fastapi.encoders import jsonable_encoder
from fastapi.responses import JSONResponse
from app.exceptions.http_resp import HttpResp

RT = TypeVar('RT')  # 返回类型
HttpCode = namedtuple('HttpResp', ['code', 'msg'])


def unified_resp(func: Callable[..., Coroutine[Any, Any, JSONResponse] | JSONResponse | Any]) -> Callable[..., Coroutine[Any, Any, JSONResponse] | JSONResponse]:
    @wraps(func)
    async def wrapper(*args, **kwargs) -> JSONResponse:
        if inspect.iscoroutinefunction(func):
            resp = await func(*args, **kwargs) or []
        else:
            resp = func(*args, **kwargs) or []
        # 装饰器的逻辑
        return JSONResponse(
            content=jsonable_encoder(
                # 正常请求响应
                {
                    'code': HttpResp.SUCCESS.code,
                    'message': HttpResp.SUCCESS.msg,
                    'data': resp
                },
                by_alias=False,
            ),
            media_type='application/json;charset=utf-8'
        )
    return wrapper


# def unified_resp(func:  AsyncFunc) -> AsyncFunc:
#     """统一响应格式
#         接口正常返回时,统一响应结果格式
#     """

#     @wraps(func)
#     async def wrapper(*args, **kwargs):
#         if inspect.iscoroutinefunction(func):
#             resp = await func(*args, **kwargs) or []
#         else:
#             resp = func(*args, **kwargs) or []
#         return JSONResponse(
#             content=jsonable_encoder(
#                 # 正常请求响应
#                 {'code': HttpResp.SUCCESS.code,
#                     'msg': HttpResp.SUCCESS.msg, 'data': resp},
#                 by_alias=False,
#                 # 自定义日期时间格式编码器
#                 # custom_encoder={
#                 #     datetime: lambda dt: dt.replace(tzinfo=pytz.utc).astimezone(
#                 #         pytz.timezone(get_settings().timezone))
#                 #     .strftime(get_settings().datetime_fmt)}),
#                 # media_type='application/json;charset=utf-8'
#             )
#         )

#     return wrapper


# T = TypeVar('T')


# def my_decorator(func: Callable[..., Coroutine[Any, Any, T]]) -> Callable[..., Coroutine[Any, Any, T]]:
#     @wraps(func)
#     async def wrapper(*args, **kwargs) -> T:
#         result = await func(*args, **kwargs)
#         # 在这里可以添加对 result 的处理逻辑
#         # 确保返回的类型与 T 相匹配
#         return result
#     return wrapper
